#include <iostream>
#include "UdpServer.hpp"
#include "log.hpp"
#include "InetAddr.hpp"
#include <string>
#include <memory>

void Usage(std::string str)
{
    std::cout << "Usage:\n\t" << str << " _local_port\n"
              << std::endl;
}
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }
    std::string serveip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);
    // 创建socket
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        std::cout << "socket error " << std::endl;
    }
    // 构建目标主机的socket信息
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;                         // 设置网络协议族
    server.sin_port = htons(serverport);                 // 设置服务端端口
    server.sin_addr.s_addr = inet_addr(serveip.c_str()); // 设置服务端lp地址

    std::string message;
    while (true)
    {
        std::cout << "please Enter#";
        std::getline(std::cin, message);
        sendto(sockfd, message.c_str(), message.size(), 0, (struct sockaddr *)&server, sizeof(server));
        std::cout<<"已发送信息"<<std::endl;
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        char buffer[1024];
        ssize_t n = recvfrom(sockfd, buffer, sizeof(buffer)-1, 0, (struct sockaddr*)&peer, &len);
        if(n > 0)
        {
            buffer[n] = 0;
            std::cout << "server echo# " << buffer << std::endl;
        }
    }
    return 0;
}

